package servicelearn.zx.com.clientapp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.zx.servicelearn.aidl.IMyAidlInterface;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";
    TextView testShow_tv;

    /**
     * 主线程handler，用于处理UI
     */
    Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    String msgText = (String) msg.obj;
                    if (msgText != null)
                        testShow_tv.setText("" + msgText);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testShow_tv = findViewById(R.id.testShow_tv);

    }

    private IMyAidlInterface myService;
    ServiceConnection myServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = IMyAidlInterface.Stub.asInterface(service);
            try {
                int c = myService.plus(1, 2);
                int d = myService.muti(1, 2);
                Log.e(TAG, "IMyAidlInterface exc" + c);//
                Log.e(TAG, "IMyAidlInter" +
                        "face exc" + d);//
                mainHandler.sendMessage(mainHandler.obtainMessage(1, "c:" + c + "d：" + d));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
//            unbindService(myServiceConnection);
//bindService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    public void bindServiceTest(View view) {
        Intent intent = new Intent("com.zx.servicelearn.aidl.IMyAidlInterface");
//        Intent intent = new Intent(this, MyService4.class);
//        intent.setAction("com.zx.servicelearn.MyService4");//你定义的service的action
//        intent.setPackage("com.zx.servicelearn");//这里你需要设置服务端应用的包名

        //隐式启动
        final Intent eintent = new Intent(createExplicitFromImplicitIntent(this, intent));
        bindService(eintent, myServiceConnection, BIND_AUTO_CREATE);//
    }


    public void unBindServiceTest(View view) {//
        try {
            unbindService(myServiceConnection);
        } catch (Exception e) {

        }
    }


    public void bindServiceTest2(View view) {
        Intent intent = new Intent("com.zx.servicelearn.service.MyService5");
//        Intent intent = new Intent(this, MyService4.class);
//        intent.setAction("com.zx.servicelearn.MyService4");//你定义的service的action
//        intent.setPackage("com.zx.servicelearn");//这里你需要设置服务端应用的包名

        //隐式启动
        final Intent eintent = new Intent(createExplicitFromImplicitIntent(this, intent));
        bindService(eintent, myServiceConnection2, BIND_AUTO_CREATE);//
    }

    Messenger mService;
    boolean mBound;
    ServiceConnection myServiceConnection2 = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mBound = false;

        }
    };


    public void unBindServiceTest2(View view) {//
        try {
            if (mBound) {
                unbindService(myServiceConnection2);
                mBound = false;
            }
        } catch (Exception e) {

        }
    }

    int MSG_SAY_HELLO = 1;

    //调用此方法时会发送信息给服务端
    public void sayHello(View v) {
        if (!mBound) return;
        //发送一条信息给服务端
        Message msg = Message.obtain(null, MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(myServiceConnection2);
            mBound = false;
        }
    }

    /***
     * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,
     * "java.lang.IllegalArgumentException: Service Intent must be explicit"
     *
     * If you are using an implicit intent, and know only 1 target would answer this intent,
     * This method will help you turn the implicit intent into the explicit form.
     *
     * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466
     * @param context
     * @param implicitIntent - The original implicit intent
     * @return Explicit Intent created from the implicit original intent
     */
    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }
}
